package com.md.config.database.slave.balancer;

import com.md.config.database.slave.DataSourceProperty;
import com.md.util.ObjectUtil;

import java.util.List;
import java.util.Random;

public class WeightSlaveSourceLoadBalancer extends ISlaveSourceLoadBalancer {
  private final Random random;

  public WeightSlaveSourceLoadBalancer() {
    this.random = new Random();
  }

  @Override
  public String load(final List<DataSourceProperty> dataSourceConfigs) {
    if (ObjectUtil.isEmpty(dataSourceConfigs)) {
      return null;
    }
    int totalWeight = dataSourceConfigs.stream().mapToInt(DataSourceProperty::getWeight).sum();
    int randomWeight = random.nextInt(totalWeight);
    int currentWeight = 0;
    for (DataSourceProperty dataSourceConfig : dataSourceConfigs) {
      currentWeight += dataSourceConfig.getWeight();
      if (randomWeight < currentWeight) {
        return dataSourceConfig.getUnique();
      }
    }
    return null;
  }

}
